$(function() {
//Declare variable
var 	tips = $( ".validateTips" ),
		button_name="",
		url="a_order_view.php", 
 		ID="",
		colspan=0;
		mode="",
		branchID="",
		rowSelect="";
		OrderNo="";
		ID=$("#val").val();
		mode=$("#mode").val();
		branchID=$("#branch").val();

		if (mode=='c') {
			colspan=8;
		}else if (mode=='d') {
			colspan=6;
		}else if (mode=='cl') {
			colspan=8;
		}else{
			colspan=6;
		}
		//Load First page
		LoadData(1, ID);
	
		//Show Loading bar			
		function showLoader(){
			$( "#resultData tbody:first" ).prepend( "<tr>"
						+"<td colspan="+colspan+" class='search-background'>"
						+"<label><img src='./images/ajax-loader.gif'/></label>"
						+"</td>"
						+"</tr>" ); 
			 $('.search-background').fadeIn(900,0);
		}
		//Hide Loading bar			
		function hideLoader(){
			$('.search-background').fadeOut(300);
			$( "#resultData tbody tr" ).remove();
		};
		
				
		//Close Dialog
		$( "#dialog:ui-dialog" ).dialog( "destroy" );
		
		//Confirm Dialog
		$( "#dialog-confirm" ).dialog({
			resizable: false,
			height:160,
			zIndex:9999,
			autoOpen: false,
			modal: true
		});
		
 
		$("#amt_c").live('click',function(){
		 //alert('dd');
			$(this).select();
			$(this).numeric();
		});
		
		$("#amt_cl").live('click',function(){
		 //alert('dd');
			$(this).select();
			$(this).numeric();
		});
		
		$("#amt_cl").live('keyup',function(){
			var RemainHO = new Number($(this).parent().parent().find("span[name=HOSendBack]").attr('innerHTML').replace(',','').replace(',',''));
			var InputAmt = new Number($(this).parent().parent().find("input[name=amt_cl]").val().replace(',','').replace(',',''));
			//alert(RemainHO);
			if (InputAmt > RemainHO){
				alert('Input amount more than Head Office amount');
				$(this).parent().parent().find("input[name=amt_cl]").val(RemainHO);
			}
		});	
		
		$("#amt_c").live('keyup',function(){
			var RemainHO = new Number($(this).parent().parent().find("span[name=remainHo]").attr('innerHTML').replace(',','').replace(',',''));
			var InputAmt = new Number($(this).parent().parent().find("input[name=amt_c]").val().replace(',','').replace(',',''));
			if (InputAmt > RemainHO){
				alert('Input amount more than remain amount');
				$(this).parent().parent().find("input[name=amt_c]").val(RemainHO);
			}
		});
		//b=false , don't gennerate paging
		function LoadData(page,id){
			$( "#resultData tbody tr" ).remove();
			
			//Show loading
			showLoader();
			//set criteria
			var dataset={'m':'view','id':id,'page':page,'type':mode};

			$.post(url,dataset,function(data){
				//hide loading
			 //alert(data);
				hideLoader();
				var obj=eval("(" + data + ")");
				var ar=eval("(" + obj['header'] + ")");
 
				OrderNo=ar['OrderNo'];
				$("#iCode").attr('innerHTML',(ar['OrderNo']));
				$("#iName").attr('innerHTML',(ar['BranchName']));
				$("#iStatus").attr('innerHTML',(ar['Status']));
				//CreateDate
				$("#dtCreatedDate").attr('innerHTML',(ar['CreatedDate']));
				$("#lblCreatedBy").attr('innerHTML',(ar['CreatedBy']));
				$("#iRowOrderDate").hide();
				$("#iRowConfirmDate").hide();
				$("#iRowCloseDate").hide();
				if (ar['iStatus']==2){
					//SendDate
					$("#iRowOrderDate").show();
					$("#dtODate").attr('innerHTML',(ar['OrderDate']));
					$("#lblOBy").attr('innerHTML',(ar['OrderBy']));

				}else if (ar['iStatus']==3){
					//Return Date
					$("#iRowOrderDate").show();
					$("#dtODate").attr('innerHTML',(ar['OrderDate']));
					$("#lblOBy").attr('innerHTML',(ar['OrderBy']));
					
					$("#iRowConfirmDate").show();
					$("#dtConfirmDate").attr('innerHTML',(ar['ConfirmDate']));
					$("#lblConfirmBy").attr('innerHTML',(ar['ConfirmBy']));
					
					//ClosedDate
					$("#iRowCloseDate").hide();

				}else if (ar['iStatus']==4){
					$("#iRowOrderDate").show();
					$("#iRowConfirmDate").show();
					$("#iRowCloseDate").show();
					$("#dtODate").attr('innerHTML',(ar['OrderDate']));
					$("#lblOBy").attr('innerHTML',(ar['OrderBy']));
					$("#dtConfirmDate").attr('innerHTML',(ar['ConfirmDate']));
					$("#lblConfirmBy").attr('innerHTML',(ar['ConfirmBy']));					
					$("#dtClosedDate").attr('innerHTML',(ar['ClosedDate']));
					$("#lblClosedBy").attr('innerHTML',(ar['ClosedBy']));
				}else{
					$("#iRowOrderDate").hide();
					$("#iRowConfirmDate").hide();
					$("#iRowCloseDate").hide();
				}
 
				$( "#resultData tbody tr" ).remove();
				
				$( "#resultData tbody" ).append(obj['data']);
				
				//set row 
				$("#rowCount").attr('innerHTML',obj['rows']);
				
				if (mode=='d'){
					//set page
					 
						var p="<ul>";
						for (var i=parseInt(obj['totalpage']);i >0 ;i--){
							p = p +'<li id="'+i+'">'+i+'</li>';
						}
						p = p+"</ul>";
						$("#paging_button ul").remove();
						$("#paging_button").append(p);
						 
					 
					$("#"+page).css({'background-color' : '#006699'});
				}
			
			});
			
		}
		//Order -> Send order from branch to HO
		$("#btnSend").live('click' ,function(){
			$("#dialog-confirm").dialog("open");
			$("#dialog-confirm").dialog("option","buttons",	{
				"Send": function() {
					$.ajax({
							type: 'POST',
							cache: false,
							url: url,
							data: {"m":"send"
									,"id":ID
									,"no":OrderNo
									,"branchname":$("#iName").attr('innerHTML')
									,"itemnumber":$("#rowCount").attr('innerHTML')
								},
							success: function(data){
								//alert( "Completed!!") ;
								$("#dialog-confirm").dialog( "close" );
								history.back(-1);
							}
						});
					

				},
				Cancel: function() {
						$( this ).dialog( "close" );
				}
			});
	 
		});
	
		//Check -> after branch order product
		$("#btnCheck").click(function(){
			var arlist=[];
			var flag=true;
			//Get value from table
			$('#resultData tbody tr').each(function() {
				// order id detail
				var oid = $(this).find("td").eq(1).html();     //ID
				// order amount
				var pid = $(this).find("td").eq(2).html();     //ID
			 
				var amt = $(this).find("input[name=amt_c]").val().replace(',','').replace(',','') ;   
				
				var RemainHOAmt = $(this).find("span[name=remainHo]").attr('innerHTML').replace(',','').replace(',','');
				
				if (isNaN(amt) || amt==''){
					amt=0
				}
				if ( parseInt(RemainHOAmt)<parseInt(amt)){
					 
					alert('Please check remain amount again!!.');
					flag=false;
					return;
				}
				arlist.push({'id': oid , 'amt':amt,'pid':pid });
			 });	
			 
			 if (flag){
				$("#dialog-confirm").dialog("open");
				$("#dialog-confirm").dialog("option","buttons",	{
						"Confirm": function() {
							// alert(arlist);
							 $.ajax({
								type: 'POST',
								cache: false,
								url: url,
								data: {"m":"check","o_id":ID,"var":arlist,"no":OrderNo,"branchid":branchID},
								success: function(data){
									//alert(data);
									// alert( "Completed!!") ;
									$("#dialog-confirm").dialog( "close" );
									history.back(-1);
								}
							});
						

						},
						Cancel: function() {
							$( this ).dialog( "close" );
					}
				});
			}
		});
		
		//confirm product
		$("#btnConfirm").live('click' ,function(){
			var arlist=[];
				$("#dialog-confirm").dialog("open");
				$("#dialog-confirm").dialog("option","buttons",	{
					"Confirm": function() {

					//Get value from table
						$('#resultData tbody tr').each(function() {
							// order id detail
							var oid = $(this).find("td").eq(1).html();     //ID
							//pid 
							var pid = $(this).find("td").eq(2).html();     //ID
							//amtfrom Ho 
							var ho_amt = $(this).find("span[name=HOSendBack]").attr('innerHTML').replace(',','').replace(',',''); //.eq(8).html();     //ID
							// alert(ho_amt);
							// order amount
							var amt = $(this).find("input[name=amt_cl]").val().replace(',','').replace(',','');  
				
							if (isNaN(amt) || amt==''){
								amt=0
							}
							arlist.push({'id': oid,'amt':amt,'pid':pid,'h_amt':ho_amt });
						 });
						 
						 $.ajax({
							type: 'POST',
							cache: false,
							url: url,
							data: {"m":"confirm"
								,"o_id":ID
								,"no":OrderNo
								,"var":arlist
								,"branchid":branchID
								,"branchname":$("#iName").attr('innerHTML')
								},
							success: function(data){
							 //	alert(data);
							//	alert( "Completed!!") ;
								$("#dialog-confirm").dialog( "close" );
								history.back(-1);
							}
						});
										
					 	 
				 	},
					Cancel: function() {
						$( this ).dialog( "close" );
				}
			});		
		});
		

	$("#btnBack").live('click',function(){
		//alert('d');
		history.back(-1);
	});
	
	$("#paging_button li").live('click',function(){
		$("#paging_button li").css({'background-color' : ''});
 		LoadData(this.id,ID);

	});
});
	